package com.cino.proxy;

import com.cino.common.Invocation;
import com.cino.common.URL;
import com.cino.loadbalance.Loadbalance;
import com.cino.protocol.HttpClient;
import com.cino.register.MapRemoteRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class ProxyFactory {

    public static <T> T getProxy(Class interfaceClass){

        Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Invocation invocation = new Invocation(interfaceClass.getName(),
                        method.getName(),
                        method.getParameterTypes(),
                        args);

                HttpClient httpClient = new HttpClient();

                //服务发现
                List<URL> list = MapRemoteRegister.get(interfaceClass.getName());

                //负载均衡
                //负载均衡的意思是随机从里面选一个
                URL url = Loadbalance.random(list);

                String result = httpClient.send(url.getHostname(),url.getPort(),invocation);
                return result;
            }
        });
        return (T)proxyInstance;
    }
}
